<template>
	<view class="content-box">
		<navbar :fixed="true" :bgColor="'#fff'" :title="t('service.zxkf')" :leftIcon="true"></navbar>
		
		<view class="char-box">
			<!-- 使用scroll-view实现下滑加载 -->
			<scroll-view 
				class="chat-container" 
				scroll-y="true" 
				:refresher-enabled="true"
				:refresher-triggered="isLoadingMore"
				@refresherrefresh="loadMoreHistory"
				@scrolltoupper="loadMoreHistory"
				:upper-threshold="50"
				:scroll-top="scrollTop"
				:scroll-into-view="scrollIntoView"
			>
				<!-- 加载更多提示 -->
				<view v-if="isLoadingMore && messageList.length > 0" class="loading-more">
					<text>{{ t('common.loading') || '加载中...' }}</text>
				</view>
				
				<!-- 没有更多消息提示 -->
				<view v-if="!hasMoreHistory && messageList.length > 0" class="no-more">
					<text>没有更多消息了</text>
				</view>
				
				<!-- 消息列表 -->
				<view v-for="(message, index) in messageList" :key="message.id || index" :class="['message', message.type === 'service' ? 'service-message' : 'user-message']">
					<!-- 客服消息布局 -->
					<template v-if="message.type === 'service'">
						<!-- 客服头像 -->
						<image class="avatar" :src="message.senderAvatar || '/static/image/avatar.png'" mode="aspectFill"></image>
						
						<view class="message-content">
							<!-- 客服名称 -->
							<view class="service-name">{{ message.senderName || t('service.gfkf') }}</view>
							
							<view class="message-box">
								<!-- 消息气泡 -->
								<view class="message-bubble service-bubble">
									<!-- 文本消息 -->
									<text v-if="message.contentType === 1">{{ message.text }}</text>
									<!-- 图片消息 -->
									<image v-else-if="message.contentType === 2" :src="message.picUrl" mode="aspectFit" class="message-image" @click="previewImage(message.picUrl)"></image>
								</view>
								
								<!-- 消息时间 -->
								<view class="message-time">{{ message.time }}</view>
							</view>
						</view>
					</template>
					
					<!-- 用户消息布局 -->
					<template v-else>
						<view class="message-content user-content">
							<view class="message-box">
								<!-- 消息气泡 -->
								<view class="message-bubble user-bubble">
									<!-- 文本消息 -->
									<text v-if="message.contentType === 1">{{ message.text }}</text>
									<!-- 图片消息 -->
									<image v-else-if="message.contentType === 2" :src="message.picUrl" mode="aspectFit" class="message-image" @click="previewImage(message.picUrl)"></image>
								</view>
								
								<!-- 消息时间 -->
								<view class="message-time">{{ message.time }}</view>
							</view>
						</view>
						
						<!-- 用户头像 -->
						<image class="avatar" :src="userInfo?.avatar || '/static/image/avatar.png'" mode="aspectFill"></image>
					</template>
				</view>
				
				<!-- 占位元素，用于滚动到底部 -->
				<view id="bottom-anchor" class="bottom-anchor"></view>
			</scroll-view>
		</view>
		
		<!-- 输入框 -->
		<view class="input-box">
			<view class="input-container">
				<input 
					v-model="messageText" 
					:placeholder="t('service.qsr')" 
					class="message-input"
					:focus="inputFocus"
					@focus="onInputFocus"
					@blur="onInputBlur"
					@confirm="sendMessage"
				/>
				<view class="input-actions">
					<view class="action-btn" @click="chooseImage">
						<image src="/static/icon/attachment.svg" mode="aspectFit" class="action-icon"></image>
					</view>
					<view class="send-btn" @click="sendMessage" :class="{ 'active': messageText.trim() }">
						<image :src="sendIcon" mode="aspectFit" class="send-icon"></image>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted, onUnmounted, nextTick } from 'vue';
	import { useI18n } from 'vue-i18n';
	import navbar from '@/components/navbar/navbar.vue';
	import serviceApi from '@/api/service.js';
	import TokenManager from '@/utils/token.js';
	import store from '@/utils/store.js';
	import { getWebSocketConfig } from '@/utils/config.js';
	
	const { t } = useI18n();
	
	// ==================== 工具函数 ====================
	
	/**
	 * 格式化时间戳为时分格式
	 */
	const formatTime = (timestamp) => {
		const date = new Date(timestamp);
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		return `${hours}:${minutes}`;
	};
	
	// ==================== 基础数据 ====================
	const userInfo = ref(null);
	const messageText = ref('');
	const inputFocus = ref(false);
	const sendIcon = ref('/static/icon/send.svg'); // 发送图标状态
	
	// ==================== 消息列表 ====================
	const messageList = ref([]);
	
	// ==================== 分页相关 ====================
	const currentPage = ref(1);
	const pageSize = ref(20);
	const hasMoreHistory = ref(true);
	const isLoadingMore = ref(false);
	
	// ==================== 滚动相关 ====================
	const scrollTop = ref(0);
	const scrollIntoView = ref('');
	
	// ==================== WebSocket相关 ====================
	let websocket = null;
	const wsConnected = ref(false);
	
	// ==================== 核心方法 ====================
	
	/**
	 * 初始化页面
	 */
	const initPage = async () => {
		// 获取用户信息（优先从store获取详细用户信息）
		try {
			await store.actions.fetchUserInfo();
			userInfo.value = store.state.userInfo;
		} catch (error) {
			// 如果获取详细用户信息失败，使用本地存储的用户信息
			userInfo.value = TokenManager.getUserInfo();
		}
		
		// 加载初始消息
		await loadInitialMessages();
		
		// 连接WebSocket
		connectWebSocket();
		
		// 滚动到底部
		setTimeout(scrollToBottom, 100);
	};
	
	/**
	 * 加载初始消息（第一页）
	 */
	const loadInitialMessages = async () => {
		try {
			const response = await serviceApi.getMessageHistory({
				pageNo: 1,
				pageSize: pageSize.value
			});

			if (response?.code === 0 && response.data?.list) {
				const messages = processMessages(response.data.list);
				messageList.value = messages;

				// 更新分页状态
				currentPage.value = 1;
				hasMoreHistory.value = response.data.list.length >= pageSize.value;
			}
		} catch (error) {
			uni.showToast({ title: '加载消息失败', icon: 'none' });
		}
	};
	
	/**
	 * 加载更多历史消息
	 */
	const loadMoreHistory = async () => {
		if (isLoadingMore.value || !hasMoreHistory.value) {
			return;
		}

		try {
			isLoadingMore.value = true;
			const nextPage = currentPage.value + 1;

			const response = await serviceApi.getMessageHistory({
				pageNo: nextPage,
				pageSize: pageSize.value
			});

			if (response?.code === 0 && response.data?.list) {
				const newMessages = processMessages(response.data.list);

				if (newMessages.length > 0) {
					// 将新消息添加到列表开头（历史消息在前）
					messageList.value = [...newMessages, ...messageList.value];
					currentPage.value = nextPage;
				}

				// 更新是否还有更多消息
				hasMoreHistory.value = newMessages.length >= pageSize.value;
			}
		} catch (error) {
			uni.showToast({ title: '加载失败', icon: 'none' });
		} finally {
			isLoadingMore.value = false;
		}
	};
	
	/**
	 * 处理消息数据
	 */
	const processMessages = (messages) => {
		return messages.map(msg => {
			let text = '';
			let picUrl = '';
			
			// 解析content字段中的JSON数据
			try {
				if (msg.contentType === 1 && msg.content) {
					// 文本消息：解析content中的JSON
					const contentObj = JSON.parse(msg.content);
					text = contentObj.text || '';
				} else if (msg.contentType === 2 && msg.content) {
					// 图片消息：解析content中的JSON
					const contentObj = JSON.parse(msg.content);
					picUrl = contentObj.picUrl || '';
				}
			} catch (e) {
				// 如果解析失败，使用原始content作为文本
				if (msg.contentType === 1) {
					text = msg.content;
				}
			}
			
			return {
				id: msg.id,
				type: msg.senderType === 1 ? 'user' : 'service',
				text: text,
				contentType: msg.contentType,
				picUrl: picUrl,
				time: formatTime(msg.createTime),
				createTime: msg.createTime,
				senderName: msg.senderName,
				senderAvatar: msg.senderAvatar
			};
		}).sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
	};
	
	/**
	 * 连接WebSocket
	 */
	const connectWebSocket = () => {
		const token = TokenManager.getAccessToken();
		if (!token) {
			console.error('❌ 无token，无法连接WebSocket');
			return;
		}

		// 使用配置化的WebSocket URL
		const wsConfig = getWebSocketConfig();
		const wsUrl = `${wsConfig.baseUrl}?token=${token}`;

		websocket = uni.connectSocket({
			url: wsUrl,
			success: () => console.log('WebSocket连接请求发送成功')
		});
		
		websocket.onOpen(() => {
			wsConnected.value = true;
		});

		websocket.onMessage((event) => {
			handleWebSocketMessage(event.data);
		});

		websocket.onError((error) => {
			wsConnected.value = false;
			console.error('❌ WebSocket连接错误:', error);
		});

		websocket.onClose(() => {
			wsConnected.value = false;
		});
	};
	
	/**
	 * 处理WebSocket消息
	 */
	const handleWebSocketMessage = (data) => {
		try {
			const message = JSON.parse(data);

			if (message.type === 'customer_message') {
				// 单条新消息
				let text = '';
				let picUrl = '';
				
				// 解析content字段中的JSON数据
				try {
					if (message.data.contentType === 1 && message.data.content) {
						// 文本消息：解析content中的JSON
						const contentObj = JSON.parse(message.data.content);
						text = contentObj.text || '';
					} else if (message.data.contentType === 2 && message.data.content) {
						// 图片消息：解析content中的JSON
						const contentObj = JSON.parse(message.data.content);
						picUrl = contentObj.picUrl || '';
					}
				} catch (e) {
					// 如果解析失败，使用原始content作为文本
					if (message.data.contentType === 1) {
						text = message.data.content;
					}
				}
				
				const newMessage = {
					id: message.data.id,
					type: message.data.senderType === 1 ? 'user' : 'service',
					text: text,
					contentType: message.data.contentType,
					picUrl: picUrl,
					time: formatTime(message.data.createTime),
					createTime: message.data.createTime,
					senderName: message.data.senderName,
					senderAvatar: message.data.senderAvatar
				};
				
				// 添加到消息列表末尾
				messageList.value.push(newMessage);
				
				// 滚动到底部
				setTimeout(scrollToBottom, 100);
				
			} else if (message.type === 'customer_message_list') {
				// 历史消息列表 - 通常在页面初始化时收到，直接忽略
			}
		} catch (error) {
			console.error('❌ 处理WebSocket消息失败:', error);
		}
	};
	
	/**
	 * 发送消息
	 */
	const sendMessage = async () => {
		const text = messageText.value.trim();
		if (!text) return;

		// 切换到发送中图标
		sendIcon.value = '/static/icon/send2.svg';

		try {
			// 构建JSON格式的content
			const contentObj = {
				text: text
			};

			const response = await serviceApi.sendMessage({
				content: JSON.stringify(contentObj),
				contentType: 1
			});

			if (response?.code === 0) {
				// 清空输入框
				messageText.value = '';

				// 添加到消息列表（乐观更新）
				const newMessage = {
					id: Date.now(),
					type: 'user',
					text: text,
					contentType: 1,
					time: formatTime(new Date()),
					createTime: new Date().toISOString()
				};

				messageList.value.push(newMessage);

				// 滚动到底部
				setTimeout(scrollToBottom, 100);
			}
		} catch (error) {
			uni.showToast({ title: '发送失败', icon: 'none' });
		} finally {
			// 还原原始图标
			sendIcon.value = '/static/icon/send.svg';
		}
	};
	
	/**
	 * 选择图片
	 */
	const chooseImage = () => {
		uni.chooseImage({
			count: 1,
			success: async (res) => {
				const tempFilePath = res.tempFilePaths[0];
				await sendImageMessage(tempFilePath);
			}
		});
	};
	
	/**
	 * 发送图片消息
	 */
	const sendImageMessage = async (imagePath) => {
		// 切换到发送中图标
		sendIcon.value = '/static/icon/send2.svg';

		try {
			// 第一步：上传图片文件
			const uploadResponse = await serviceApi.uploadFile(imagePath);

			if (uploadResponse?.code === 0 || uploadResponse?.code === 200) {
				const uploadedUrl = uploadResponse.data;

				// 第二步：构建JSON格式的content
				const contentObj = {
					picUrl: uploadedUrl
				};

				// 第三步：发送图片消息
				const response = await serviceApi.sendMessage({
					content: JSON.stringify(contentObj),
					contentType: 2
				});

				if (response?.code === 0) {
					const newMessage = {
						id: Date.now(),
						type: 'user',
						contentType: 2,
						picUrl: uploadedUrl,
						time: formatTime(new Date()),
						createTime: new Date().toISOString()
					};

					messageList.value.push(newMessage);
					setTimeout(scrollToBottom, 100);
				}
			} else {
				throw new Error('图片上传失败');
			}
		} catch (error) {
			uni.showToast({ title: '发送失败', icon: 'none' });
		} finally {
			// 还原原始图标
			sendIcon.value = '/static/icon/send.svg';
		}
	};
	
	/**
	 * 预览图片
	 */
	const previewImage = (url) => {
		uni.previewImage({
			urls: [url],
			current: url
		});
	};
	
	/**
	 * 滚动到底部
	 */
	const scrollToBottom = () => {
		scrollIntoView.value = 'bottom-anchor';
		setTimeout(() => {
			scrollIntoView.value = '';
		}, 100);
	};
	
	/**
	 * 输入框聚焦
	 */
	const onInputFocus = () => {
		inputFocus.value = true;
		setTimeout(scrollToBottom, 300);
	};
	
	/**
	 * 输入框失焦
	 */
	const onInputBlur = () => {
		inputFocus.value = false;
	};
	
	// ==================== 生命周期 ====================
	onMounted(() => {
		initPage();
	});
	
	onUnmounted(() => {
		if (websocket) {
			websocket.close();
		}
	});
</script>

<style lang="scss" scoped>
	.content-box {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}
	
	.char-box {
		flex: 1;
		overflow: hidden;
		margin-top: 88rpx;
		margin-bottom: 120rpx;
	}
	
	.chat-container {
		height: 100%;
		padding: 20rpx;
	}
	
	.loading-more {
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 28rpx;
	}
	
	.no-more {
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 28rpx;
	}
	
	.message {
		display: flex;
		margin-bottom: 30rpx;
		
		&.service-message {
			justify-content: flex-start;
		}
		
		&.user-message {
			justify-content: flex-end;
		}
	}
	
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin: 0 20rpx;
	}
	
	.message-content {
		max-width: 500rpx;
		
		&.user-content {
			text-align: right;
		}
	}
	
	.service-name {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 10rpx;
	}
	
	.message-box {
		display: flex;
		flex-direction: column;
		
		.user-content & {
			align-items: flex-end;
		}
	}
	
	.message-bubble {
		padding: 20rpx;
		border-radius: 20rpx;
		max-width: 100%;
		word-wrap: break-word;
		
		&.service-bubble {
			background-color: #fff;
			border: 1rpx solid #e5e5e5;
		}
		
		&.user-bubble {
			background-color: #007aff;
			color: #fff;
		}
	}
	
	.message-image {
		max-width: 300rpx;
		max-height: 300rpx;
		border-radius: 10rpx;
	}
	
	.message-time {
		font-size: 22rpx;
		color: #999;
		margin-top: 10rpx;
	}
	
	.bottom-anchor {
		height: 1rpx;
	}
	
	.input-box {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-top: 1rpx solid #e5e5e5;
		padding: 20rpx;
	}
	
	.input-container {
		display: flex;
		align-items: center;
		background-color: #f8f8f8;
		border-radius: 25rpx;
		padding: 15rpx 20rpx;
		border: 1rpx solid transparent;
		transition: border-color 0.3s;
		
		&:focus-within {
			border-color: rgba(59, 130, 246, 1);
		}
	}
	
	.message-input {
		flex: 1;
		border: none;
		outline: none;
		background: transparent;
		font-size: 28rpx;
		color: #333;
		padding: 0;
		font-family: SourceHanSansSC;
	}
	
	.input-actions {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
	}
	
	.action-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		
		.action-icon {
			width: 40rpx;
			height: 40rpx;
		}
	}
	
	.send-btn {
		width: 80rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(90deg, rgba(12, 193, 155, 1) 0%, rgba(91, 220, 222, 1) 34.03%, rgba(5, 145, 198, 1) 65.97%, rgba(2, 120, 220, 1) 100%);
		border-radius: 20rpx;
		transition: opacity 0.3s;
		opacity: 0.6;
		
		&.active {
			opacity: 1;
		}
		
		.send-icon {
			width: 32rpx;
			height: 32rpx;
		}
	}
</style>